import 'dart:async';
import 'dart:convert';
import 'dart:math';

import 'package:get/get.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

class WebSocketController extends GetxController {
  late WebSocketChannel _channel;
  late Timer _timer;
  final String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjQzMjM4NDU2MTYsImlhdCI6MTY5NTM2MjgwOCwidWlkIjoxfQ.B6wj2_Or-F7ZufVUj2qExPxUb0IwXzcpUpZw5Jhnkwg";

  @override
  void onInit() {
    _connect();
    super.onInit();
  }

  @override
  void onClose() {
    _channel.sink.close();
    _timer.cancel();
    super.onClose();
  }

  _connect() async {
    print("websoket connecting....");

    const wsUrl = "ws://im.zs2020516.com/acc";
    _channel = WebSocketChannel.connect(Uri.parse(wsUrl), protocols: [token]);
    _channel.stream.listen(
      (message) {
        print(message);
      },
      onError: (err) {
        print("err ===>: $err");
        _timer = Timer(const Duration(seconds: 3), () {
          //延时执行的代码
          _connect();
          print("3秒后执行");
        });
      },
    );
    _login();
  }

  _login() {
    var seq = Random().nextInt(10000000) + 1;
    Map<String, dynamic> map = {
      "cmd": "login",
      "data": {
        "seq": seq.toString(),
        "appId": 101,
        "token": token,
      },
    };

    String jsonStringB = json.encode(map);
    print("login message: $jsonStringB");

    _channel.sink.add(jsonStringB);
  }

  send(String message) {
    var seq = Random().nextInt(10000000) + 1;
    Map<String, dynamic> map = {
      "cmd": "msg",
      "data": {
        "seq": seq.toString(),
        "appId": 101,
        "token": token,
        "msg": message,
      },
    };

    String jsonStringB = json.encode(map);
    print("send message: $jsonStringB");

    _channel.sink.add(jsonStringB);
  }
}
